import { defineStore, type StoreDefinition } from "pinia";
import userInfoApi from "@/api/userInfo";
import { ElMessage } from "element-plus";

export const useUserInfoStore:StoreDefinition = defineStore("userInfo", {
   state: () => ({
      token: localStorage.getItem("TOKEN"),
   }),
   actions: {
      //登录
      async login(form: any) {
         try {
            let result = await userInfoApi.login(form);
            this.token = "37f02526-e731-4b13-8fdf-32e67421d014";
            let token = "37f02526-e731-4b13-8fdf-32e67421d014";
            localStorage.setItem("TOKEN", token);
         } catch (error) {
            ElMessage.error("登陆失败,请重试");
            return Promise.reject(error);
         }
      },
      //注册
      async register(form: any) {
         try {
            let result = await userInfoApi.register(form);
            if (!((result as any).code == 200)) {
               ElMessage.error(result.message);

            } else {
               ElMessage.success("注册成功");
            }
            console.log(result);
         } catch (error) {
            ElMessage.error("注册失败,请重试");
            return Promise.reject(error);
         }
      },
      //退出
      async Logout() {
         try {
            await userInfoApi.reqLogout();
            this.token = "";
         } catch (error) {
            ElMessage.error("退出登录失败");
            return Promise.reject(error);
         }
      },
      //获取验证码
      async getCode(phone: string) {
         try {
            let result = await userInfoApi.reqCode(phone);
            if (result && result.code == 200) {
               return result;
            }
         } catch (error) {
            ElMessage.error("获取验证码失败");
            return Promise.reject(error);
         }
      },
   },
});
